﻿using Biotech.Log;
using MaterialDesignThemes.Wpf;
using project.B12.application;
using project.B12.application.Ioc;
using project.B12.application.Views.Control;
using project.B12.application.Views.Dialogs;
using project.B12.IRepository;
using project.B12.IService;
using project.B12.Model.BaseModel;
using project.B12.Model.Common;
using project.B12.Model.Enums;
using project.B12.Model.Models;
using project.B12.Service;
using SixLabors.ImageSharp;
using software.Common.MVVM;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;
using WPFDevelopers.Helpers;
using Application = System.Windows.Application;

namespace project.B12.ViewModels
{
    public class AnalyseViewModel : ObservableObject
    {
        #region Service
        private PublicResourceViewModel _publicResourceViewModel { get; set; }
        private IResultReportedRepository resultReportedRepository { get; set; }
        public IServiceImageProcessing serviceImageProcessing { get; set; }
        public IServiceIdentification serviceIdentification { get; set; }
        public IMICPlateMes antibioticConcentrationMes { get; set; }
        public IHisRepository hisRepository { get; set; }
        public IWorkSequence workSequence { get; set; }
        public IServiceDevice serviceDevice { get; set; }
        #endregion

        #region Model
        private int tabControlIndex = 0;//Tab控件选择的索引

        private Dictionary<string, TemplateEnum> templates;//界面可选模板类型

        private ObservableCollection<Test> _report;

        private string _plateType = string.Empty;
        private string _bacterialName = string.Empty;
        private string _plateId = string.Empty;
        private string _sampleId = string.Empty;

        //public ObservableCollection<WellPlateItem> WellPlateItems { get; set; } = new();

        private ObservableCollection<WellPlateItem> wellPlateItems { get; set; }
        public ObservableCollection<WellPlateItem> WellPlateItems
        {
            get { return wellPlateItems; }
            set
            {
                wellPlateItems = value;
                this.RaisePropertyChanged();
            }
        }

        private bool isVisible = true;
        public bool IsVisible
        {
            get { return isVisible; }
            set { isVisible = value; this.RaisePropertyChanged(); }
        }

        private string result_WellPlateID;
        public string Result_WellPlateID
        {
            get => result_WellPlateID;
            set
            {
                result_WellPlateID = value;
                this.RaisePropertyChanged();
            }
        }

        private DateTime? startDatePickerValue;
        public DateTime? StartDatePickerValue
        {
            get { return startDatePickerValue; }
            set
            {
                startDatePickerValue = value;
                this.RaisePropertyChanged();
            }
        }

        private DateTime? endDatePickerValue;
        public DateTime? EndDatePickerValue
        {
            get { return endDatePickerValue; }
            set
            {
                endDatePickerValue = value;
                this.RaisePropertyChanged();
            }
        }

        public int TabControlIndex
        {
            get { return tabControlIndex; }
            set
            {
                tabControlIndex = value;
                if (tabControlIndex == 2)
                {
                    IsVisible = false;
                    CurrentView = new ReportTemplate() { DataContext = this };
                }
                else
                {
                    IsVisible = true;
                    CurrentView = new Template_8x12() { DataContext = this };
                }
                this.RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 所有药敏板列表
        /// </summary>
        private ObservableCollection<string> wellPlateIDList;
        public ObservableCollection<string> WellPlateIDList
        {
            get { return wellPlateIDList; }
            set { wellPlateIDList = value; this.RaisePropertyChanged(); }
        }

        /// <summary>
        /// 当前选中的药敏板
        /// </summary>
        //private string wellPlateIDItemsSelectedValue;
        //public string WellPlateIDItemsSelectedValue
        //{
        //    get { return wellPlateIDItemsSelectedValue; }
        //    set
        //    {
        //        wellPlateIDItemsSelectedValue = value;
        //        if (value != null)
        //        {
        //            if (!string.IsNullOrEmpty(value))
        //            {
        //                WellPlateIDQueryResults(value);
        //            }
        //        }
        //        this.RaisePropertyChanged();
        //    }
        //}

        public Dictionary<string, TemplateEnum> Templates
        {
            get { return templates; }
            set { templates = value; this.RaisePropertyChanged(); }
        }

        private TemplateEnum currentTemplate;//当前选择的模板
        public TemplateEnum CurrentTemplate
        {
            get { return currentTemplate; }
            set
            {
                currentTemplate = value;
                ChangeTemplate();//下拉框变更模板时，更新当前显示界面
                this.RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 分析界面当前模板视图
        /// </summary>
        private FrameworkElement currentView;//当前显示的模板界面
        public FrameworkElement CurrentView
        {
            get { return currentView; }
            set { currentView = value; this.RaisePropertyChanged(); }
        }

        /// <summary>
        /// 药敏板数据源清单, 数据根据需要显示在CurrentView中.
        /// </summary>
        private WellPlate _wellPlate;
        public WellPlate WellPlate
        {
            get { return _wellPlate; }
            set
            {
                _wellPlate = value;
                this.RaisePropertyChanged();
            }
        }

        private Table_His _currentHis;
        public Table_His CurrentHis
        {
            get { return _currentHis; }
            set { _currentHis = value; this.RaisePropertyChanged(); }
        }


        /// <summary>
        /// 当前选中的单元格.
        /// </summary>
        private Test previewWindowImageSource;//
        public Test PreviewWindowImageSource
        {
            get { return previewWindowImageSource; }
            set { previewWindowImageSource = value; this.RaisePropertyChanged(); }
        }

        private FrameworkElement previewWindowImageView;//当前显示的浏览图片界面
        public FrameworkElement PreviewWindowImageView
        {
            get { return previewWindowImageView; }
            set { previewWindowImageView = value; this.RaisePropertyChanged(); }
        }

        private string waitProgress;
        public string WaitProgress
        {
            get { return waitProgress; }
            set { waitProgress = value; this.RaisePropertyChanged(); }
        }

        #endregion

        #region Command
        public RelayCommand ResultQueryCommand => new(ResultQuery);
        public RelayCommand<int> SelectImageCommand => new(SelectImage);
        public RelayCommand<int> UpdatePositiveCommand => new(UpdatePositive);
        public RelayCommand<int> UpdateNegativeCommand => new(UpdateNegative);
        public RelayCommand<string> SelectCommand => new RelayCommand<string>((value) =>
        {
            if (!string.IsNullOrEmpty(value))
            {
                WellPlateIDQueryResults(value);
            }
        });
        public RelayCommand ExportCommand => new(Export);
        #endregion

        public AnalyseViewModel(IServiceImageProcessing _serviceImageProcessing,
                IServiceIdentification _serviceIdentification,
                IMICPlateMes _antibioticConcentrationMes,
                IHisRepository _hisRepository,
                IWorkSequence _workSequence,
                IServiceDevice _serviceDevice,
                IResultReportedRepository _resultReportedRepository)
        {
            serviceImageProcessing = _serviceImageProcessing;//图像处理服务注入
            serviceIdentification = _serviceIdentification;//数据服务注入
            antibioticConcentrationMes = _antibioticConcentrationMes;//药敏板布板信息注入
            hisRepository = _hisRepository;
            workSequence = _workSequence;
            serviceDevice = _serviceDevice;
            resultReportedRepository = _resultReportedRepository;
            _publicResourceViewModel = ViewModelLocator.PublicResourceViewModel;
            WellPlateItems = new ObservableCollection<WellPlateItem>();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public void Init()
        {
            TabControlIndex = 0;
            WellPlateIDList = new ObservableCollection<string>();
            Templates = EnumUtil.GetEnumDic<TemplateEnum>(typeof(TemplateEnum));//更新下拉列框数据源
            CurrentTemplate = TemplateEnum.Default;                                   //载入默认模板
            QueryAllWellPlateID();                                                    //刷新药敏板列表
            _ = RefreshWellPlateID();
        }

        /// <summary>
        /// 查询所有的药敏板ID
        /// </summary>
        private void QueryAllWellPlateID()
        {
            try
            {
                WellPlateItems = new ObservableCollection<WellPlateItem>(serviceImageProcessing.GetWellPlateItems(AppDomain.CurrentDomain.BaseDirectory + @"Image", hisRepository));
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.CurrentLogger.LogInfo(ex.ToString());
            }
        }

        /// <summary>
        /// 刷新药敏板列表
        /// </summary>
        /// <returns></returns>
        private async Task RefreshWellPlateID()
        {
            await Task.Run(async () =>
            {
                while (true)
                {
                    if (serviceDevice.IsUpdateWellPlateIDList)
                    {
                        QueryAllWellPlateID();
                        
                        //在 C# 中，如果调用有返回值的方法但不使用返回值，编译器会发出警告
                        //使用 _ = 可以消除这个警告
                        _ = UpdateResultReported();
                        serviceDevice.IsUpdateWellPlateIDList = false;
                    }
                    await Task.Delay(1000);
                }
            });
        }

        /// <summary>
        /// 更新结果分析
        /// </summary>
        /// <returns></returns>
        private async Task UpdateResultReported()
        {
            await Task.Run(() =>
            {
                List<Table_MonitorMes> monitorMess = serviceDevice.Items64.Where(o => o.IsReport == true).ToList();
                if (monitorMess == null || monitorMess.Count == 0)
                    return Task.CompletedTask;
                foreach (var item in monitorMess)
                {
                    SetReport(item);
                    item.IsReport = false;
                }

                return Task.CompletedTask;
            });
        }

        /// <summary>
        /// 得到结果分析
        /// </summary>
        /// <param name="item">药敏板</param>
        private void SetReport(Table_MonitorMes item)
        {
            try
            {
                string name = item.SampleID + "&" + item.PlateID;
                WellPlateIDQueryResults(name);
                List<Table_ResultReported> resultReporteds = resultReportedRepository.QueryReport(item.PlateType, item.PlateID);
                if (_report == null || _report.Count == 0)
                    return;
                if (resultReporteds == null || resultReporteds.Count == 0)
                {
                    AddOrUpdateReport(_report, CurrentHis, false);
                }
                else
                    AddOrUpdateReport(_report, CurrentHis, true);

                if (!_publicResourceViewModel.ReportTitleRows.ContainsKey(item.PlateType))
                {
                    List<string> drugNames = new List<string>();
                    foreach (var value in _report)
                        drugNames.Add(value.DrugName);
                    _publicResourceViewModel.ReportTitleRows.Add(item.PlateType, drugNames);
                }
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.CurrentLogger.LogInfo(ex.ToString());
            }
        }

        /// <summary>
        /// 添加或更新结果分析
        /// </summary>
        /// <param name="reports"></param>
        /// <param name="his">药敏板记录</param>
        /// <param name="isUpdate">是否更新</param>
        private void AddOrUpdateReport(ObservableCollection<Test> reports, Table_His his, bool isUpdate)
        {
            var temp = reports.GroupBy(o => o.BacteriaName, (bacteriaName, list) => new { BacteriaName = bacteriaName, List = list });
            foreach (var item in temp)
            {
                Dictionary<string, string> results = new Dictionary<string, string>();
                foreach (var value in item.List)
                {
                    results.Add(value.DrugName, value.MIC);
                }
                if (isUpdate)
                {
                    Table_ResultReported resultReport = resultReportedRepository.QueryReport(his.PlateType, his.PlateName).First();
                    resultReport.MicResult = results;
                    resultReport.IsUpdate = true;
                    resultReportedRepository.UpdateReport(resultReport);
                    continue;
                }

                Table_ResultReported resultReported = new Table_ResultReported()
                {
                    PlateType = his.PlateType,
                    PlateId = his.PlateName,
                    SampleId = his.BacterialID,
                    LoadTime = his.LoadTime,
                    BacterialName = item.BacteriaName,
                    IsSpecial = his.IsSpecialSample,
                    IsUpdate = isUpdate
                };
                resultReported.MicResult = results;
                resultReportedRepository.AddReport(resultReported);
            }
        }

        /// <summary>
        /// 通过选中的药敏板ID查找扫描结果
        /// </summary>
        /// <param name="value">保存在照片文件夹下的 SampleID-PlateID </param>
        private async void WellPlateIDQueryResults(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    WPF.Controls.Message.Push($"Plate ID cannot be empty.", MessageBoxImage.Warning);
                    return;
                });
            }

            try
            {
                int index = value.IndexOf("&");
                int endIndex = 0;
                if (value.Contains("h"))
                {
                    endIndex = value.LastIndexOf("-");
                    _plateId = value.Substring(index + 1, endIndex - index - 1);
                }
                else
                    _plateId = value.Substring(index + 1);
                _sampleId = value.Substring(0, index);
                var hisory = hisRepository.QueryHisByPlateName(_plateId, _sampleId);
                if (hisory == null || hisory.Count == 0)
                {
                    WPF.Controls.Message.Push($"未找到“{value}”数据记录！", MessageBoxImage.Warning);
                    return;
                }
                CurrentHis = hisory.First();
                _plateType = hisory.First().PlateType;
                _bacterialName = hisory.First().BacterialName;

                if (hisory.First().IsSpecialSample)
                {
                    QuerySpecialWellPlateResult(hisory.First(), value);
                }
                else
                {
                    QueryWellPlateResult(hisory.First(), value);
                }

                WellPlate.Report = _report;
                var resultReports = resultReportedRepository.QueryReport(_plateType, _plateId);
                if (resultReports == null || resultReports.Count == 0)
                    AddOrUpdateReport(_report, CurrentHis, false);
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.CurrentLogger.LogInfo(ex.ToString());
            }
        }

        /// <summary>
        /// 普通加样的分析结果
        /// </summary>
        /// <param name="hisory"></param>
        /// <param name="value"></param>
        private async void QueryWellPlateResult(Table_His hisory, string value)
        {
            MicroplateMes microMes = GetMicroplateMes(_plateType);
            string path = AppDomain.CurrentDomain.BaseDirectory + @"Image\" + value;
            BitmapImage[] Temp_ImageList;
            if (!IsGetBitMap(value, path, out Temp_ImageList))
                return;

            await Task.Run(() =>
            {
                MessageModel result = GetResult(path, Temp_ImageList, microMes);
                if (_publicResourceViewModel.RecordBacterias.Any(o => o == _bacterialName))
                {
                    UpdateJudgmentByRule();
                }

                if (microMes != null)
                {
                    ShowSIR(_bacterialName);
                }

                Application.Current.Dispatcher.Invoke(() =>
                {
                    if (result.Success)
                    {
                        PreviewWindowImageView = new ImageControl();
                        PreviewWindowImageSource = new Test();
                        //WPF.Controls.Message.Push($"药敏板\"{value}\"图片导入成功!", MessageBoxImage.Information);
                    }
                    else
                    {
                        WPF.Controls.Message.Push($"注意!药敏板\"{value}\"图片导入失败!\r{result.Message}", MessageBoxImage.Error);
                        LoggerFactory.Instance.CurrentLogger.LogInfo($"药敏板\"{value}\"图片导入失败!\r{result.Message}", "", "软件");
                    }
                    WaitProgress = string.Empty;
                    DialogHost.Close("Main");
                });
            }).ContinueWith(t =>
            {
                if (t.IsFaulted && DialogHost.IsDialogOpen("Main"))
                {
                    App.Current.Dispatcher.Invoke(() =>
                    {
                        DialogHost.Close("Main");
                    });

                }
            });
        }

        /// <summary>
        /// 特殊加样的分析结果
        /// </summary>
        private async void QuerySpecialWellPlateResult(Table_His hisory, string value)
        {
            _plateType = hisory.PlateType;
            MicroplateMes microMes = GetMicroplateMes(_plateType);
            string path = AppDomain.CurrentDomain.BaseDirectory + @"Image\" + value;
            BitmapImage[] Temp_ImageList;
            if (!IsGetBitMap(value, path, out Temp_ImageList))
                return;

            await Task.Run(() =>
            {
                MessageModel result = GetResult(path, Temp_ImageList, microMes);

                Dictionary<int, string> bacteriaIndex = hisory.SpecialSampleTypes
                                   .SelectMany(kv => kv.Value.Select(num => new { Number = num, Name = kv.Key })
                                   .OrderBy(x => x.Number)).ToDictionary(o => o.Number, o => o.Name);

                if (microMes != null)
                {
                    ShowSpecialSIR(bacteriaIndex);
                }

                Application.Current.Dispatcher.Invoke(() =>
                {
                    if (result.Success)
                    {
                        PreviewWindowImageView = new ImageControl();
                        PreviewWindowImageSource = new Test();
                    }
                    WaitProgress = string.Empty;
                    DialogHost.Close("Main");
                });
            }).ContinueWith(t =>
            {
                if (t.IsFaulted && DialogHost.IsDialogOpen("Main"))
                {
                    App.Current.Dispatcher.Invoke(() =>
                    {
                        DialogHost.Close("Main");
                    });
                }
            });
        }

        /// <summary>
        /// 判断是否得到图片数据
        /// </summary>
        /// <param name="value"></param>
        /// <param name="path">路径</param>
        /// <param name="Temp_ImageList"></param>
        /// <returns></returns>
        private bool IsGetBitMap(string value, string path, out BitmapImage[] Temp_ImageList)
        {
            Temp_ImageList = serviceImageProcessing.ShowAllImage(path);

            if (Temp_ImageList == null)
            {
                WPF.Controls.Message.Push($"未找到“{value}”文件夹下的图片数据或数据缺失！", MessageBoxImage.Warning);
                return false;
            }
            if (Temp_ImageList != null && Temp_ImageList.Count() != WellPlate.ImageList.Count())
            {
                WPF.Controls.Message.Push($"导入失败！目标文件夹下图片数量和模板不一致！", MessageBoxImage.Warning);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 得到图片的判读结果
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="Temp_ImageList">图像数据</param>
        /// <param name="microMes">微孔板信息</param>
        /// <returns></returns>
        private MessageModel GetResult(string path, BitmapImage[] Temp_ImageList, MicroplateMes microMes)
        {
            //显示等待对话框
            Application.Current.Dispatcher.Invoke(() =>
            {
                WaitMessage.WaitMessageView(this, "Main");
            });

            var Temp_ResultList = serviceIdentification.Identification_All(path, _plateType, _bacterialName, newProgress =>
            {
                //回调中修改 WaitProgress 的值
                WaitProgress = newProgress;
            });

            //将图片数据\判读结果数据更新到微孔板中
            MessageModel result = WellPlate.UpdateData(_plateId, Temp_ImageList, Temp_ResultList, microMes, _plateType, _bacterialName);
            return result;
        }

        private void UpdateJudgmentByRule()
        {
            var DrugNameGroup = WellPlate.ImageList.GroupBy(s => s.DrugName, (drugName, list) => new { DrugName = drugName, List = list });
            foreach (var item in DrugNameGroup)
            {
                if (item.DrugName == "+" || item.DrugName == "-")
                    continue;

                var ND = item.List.OrderBy(o => o.DrugConcentration).ToList();
                string[] rets = ND.First().Result.Split('/');
                if (Math.Max(byte.Parse(rets[0]), byte.Parse(rets[1])) < 4)
                {
                    foreach (var nd in ND)
                    {
                        string[] tempRets = nd.Result.Split('/');
                        int index = nd.Index;
                        if (byte.Parse(tempRets[0]) >= 4)
                        {
                            tempRets[0] = "-1";
                        }
                        if (byte.Parse(tempRets[1]) >= 4)
                        {
                            tempRets[1] = "-1";
                        }
                        WellPlate.ImageList[index].Result = $"{tempRets[0]}/{tempRets[1]}/{tempRets[2]}";
                    }
                }

            }
        }

        private void ShowSIR(string bacterialName)
        {
            var DrugNameGroup = WellPlate.ImageList.GroupBy(s => s.DrugName, (drugName, list) => new { DrugName = drugName, List = list });
            _report = new ObservableCollection<Test>();
            foreach (var item in DrugNameGroup)
            {
                string mic = string.Empty;
                string SIR_finally = string.Empty;
                if (item.DrugName == "+" || item.DrugName == "-")
                {
                    item.List.ToList().ForEach(s => { s.SIR = ""; });
                    continue;
                }
                //浓度从低到高排序
                var ND = item.List.OrderBy(o => o.DrugConcentration).ToList();
                bool isUpdate = item.List.Any(o => o.IsUpdate);

                mic = GetMIC(ND);
                Table_SIR tbSIR = workSequence.GetSIR(bacterialName, item.DrugName);
                float low;
                float high;
                if (tbSIR != null)
                {
                    low = float.Parse(tbSIR.S);
                    high = float.Parse(tbSIR.R);
                    item.List.ToList().ForEach(o => { o.S = tbSIR.S; o.I = tbSIR.I; o.R = tbSIR.R; });
                }
                else
                {
                    SIR_finally = "";
                    item.List.ToList().ForEach(s => { s.SIR = SIR_finally; });
                    SetTestByNullSIR(item.DrugName, mic, bacterialName, isUpdate);
                    continue;
                }
                SIR_finally = GetSIRFinally(mic, low, high);

                if (string.IsNullOrEmpty(SIR_finally))
                {
                    WPF.Controls.Message.Push($"{item.DrugName}与{bacterialName}的SIR有误！", MessageBoxImage.Warning);
                }

                item.List.ToList().ForEach(s => { s.SIR = SIR_finally; });
                Test temp = new Test()
                {
                    DrugName = item.DrugName,
                    BacteriaName = bacterialName,
                    SIRResult = GetSIRResult(SIR_finally),
                    Source = string.IsNullOrEmpty(tbSIR.Source) ? "/" : tbSIR.Source,
                    S = tbSIR.S,
                    I = tbSIR.I,
                    R = tbSIR.R,
                    MIC = mic,
                    IsUpdate = isUpdate,
                };
                _report.Add(temp);
            }
        }

        private void ShowSpecialSIR(Dictionary<int, string> bacteriaIndex)
        {
            var DrugNameGroup = WellPlate.ImageList.GroupBy(s => s.DrugName, (drugName, list) => new { DrugName = drugName, List = list }).ToList();

            _report = new ObservableCollection<Test>();
            var length = DrugNameGroup.Count();
            int index = 0;

            for (int i = 0; i < DrugNameGroup.Count(); i++)
            {
                string mic = string.Empty;
                string SIR_finally = string.Empty;
                if (DrugNameGroup[i].DrugName == "+" || DrugNameGroup[i].DrugName == "-")
                {
                    DrugNameGroup[i].List.ToList().ForEach(s => { s.SIR = ""; });
                    continue;
                }
                index++;

                bool isUpdate = DrugNameGroup[i].List.Any(o => o.IsUpdate);
                if (!bacteriaIndex.ContainsKey(index))
                {
                    SetTestByNullSIR(DrugNameGroup[i].DrugName, mic, string.Empty, isUpdate);
                    continue;
                }

                //浓度从低到高排序
                var ND = DrugNameGroup[i].List.OrderBy(o => o.DrugConcentration).ToList();
                if (_publicResourceViewModel.RecordBacterias.Any(o => o == bacteriaIndex[index]))
                {
                    ManualCorrectionResult(ND);
                }

                mic = GetMIC(ND);
                Table_SIR tbSIR = workSequence.GetSIR(bacteriaIndex[index], DrugNameGroup[i].DrugName);
                float low;
                float high;
                if (tbSIR != null)
                {
                    low = float.Parse(tbSIR.S);
                    high = float.Parse(tbSIR.R);
                    DrugNameGroup[i].List.ToList().ForEach(o => { o.S = tbSIR.S; o.I = tbSIR.I; o.R = tbSIR.R; });
                }
                else
                {
                    SIR_finally = "";
                    DrugNameGroup[i].List.ToList().ForEach(s => { s.SIR = SIR_finally; });
                    SetTestByNullSIR(DrugNameGroup[i].DrugName, mic, bacteriaIndex[index], isUpdate);
                    continue;
                }
                SIR_finally = GetSIRFinally(mic, low, high);
                if (string.IsNullOrEmpty(SIR_finally))
                {
                    WPF.Controls.Message.Push($"{DrugNameGroup[i].DrugName}与{bacteriaIndex[index]}的SIR有误！");
                }

                DrugNameGroup[i].List.ToList().ForEach(s => { s.SIR = SIR_finally; });
                Test temp = new Test()
                {
                    DrugName = DrugNameGroup[i].DrugName,
                    BacteriaName = bacteriaIndex[index],
                    SIRResult = GetSIRResult(SIR_finally),
                    Source = string.IsNullOrEmpty(tbSIR.Source) ? "/" : tbSIR.Source,
                    S = tbSIR.S,
                    I = tbSIR.I,
                    R = tbSIR.R,
                    MIC = mic,
                    IsUpdate = isUpdate,
                };
                _report.Add(temp);
            }
        }

        /// <summary>
        /// 手动更正判读结果
        /// </summary>
        /// <param name="ND"></param>
        private void ManualCorrectionResult(List<Test> ND)
        {
            string[] rets = ND.First().Result.Split('/');
            if (Math.Max(byte.Parse(rets[0]), byte.Parse(rets[1])) < 4)
            {
                foreach (var nd in ND)
                {
                    string[] tempRets = nd.Result.Split('/');
                    if (byte.Parse(tempRets[0]) >= 4)
                    {
                        tempRets[0] = "-1";
                    }
                    if (byte.Parse(tempRets[1]) >= 4)
                    {
                        tempRets[1] = "-1";
                    }
                    var result = $"{tempRets[0]}/{tempRets[1]}/{tempRets[2]}";
                    nd.Result = result;
                    WellPlate.ImageList[nd.Index].Result = result;
                }
            }
        }

        private string GetSIRResult(string sIR)
        {
            switch (sIR)
            {
                case "S":
                    return SIREnum.敏感.ToString();
                case "I":
                    return SIREnum.中介.ToString();
                case "R":
                    return SIREnum.耐药.ToString();
                case null:
                    return "异常";
            }
            return null;
        }

        private MicroplateMes GetMicroplateMes(string plateType)
        {
            MicroplateMes microMes;
            if (antibioticConcentrationMes.microplateAntibioticConcentrationMes == null || antibioticConcentrationMes.microplateAntibioticConcentrationMes.Count <= 0)
            {
                microMes = null;
            }
            else
            {
                var list = antibioticConcentrationMes.microplateAntibioticConcentrationMes.Where(m => m.name == plateType).ToList();
                if (list.Count > 0)
                {
                    microMes = list.First();
                }
                else
                {
                    microMes = null;
                }
            }
            return microMes;
        }

        private string GetMIC(List<Test> ND)
        {
            string mic = string.Empty;
            for (int i = 0; i < ND.Count; i++)
            {
                if (ND[i].Result == null)
                    continue;
                string[] rets = ND[i].Result.Split('/');
                if (Math.Max(byte.Parse(rets[0]), byte.Parse(rets[1])) < 4)
                {
                    if (i == 0)
                    {
                        mic = $"≤{ND[i].DrugConcentration}";
                    }
                    else
                    {
                        mic = $"{ND[i].DrugConcentration}";
                    }
                    break;
                }
                if (i == (ND.Count - 1))
                {
                    mic = $"≥{ND[i].DrugConcentration}";
                }
            }
            return mic;
        }

        private void SetTestByNullSIR(string drugName, string mic, string bacteria, bool isUpdate)
        {
            Test temp = new Test()
            {
                DrugName = drugName,
                BacteriaName = string.IsNullOrEmpty(bacteria) ? "/" : bacteria,
                SIRResult = "/",
                Source = "/",
                S = "/",
                I = "/",
                R = "/",
                MIC = string.IsNullOrEmpty(mic) ? "/" : mic,
                IsUpdate = isUpdate
            };
            _report.Add(temp);
        }

        private string GetSIRFinally(string mic, float low, float high)
        {
            try
            {
                string SIR_finally = null;
                if (mic.Contains("≤") && float.Parse(mic.Split('≤')[1]) <= low)
                {
                    SIR_finally = "S";
                }
                else if (mic.Contains("≥") && float.Parse(mic.Split('≥')[1]) >= high)
                {
                    SIR_finally = "R";
                }
                else if (float.Parse(mic) <= low)
                {
                    SIR_finally = "S";
                }
                else if (float.Parse(mic) >= high)
                {
                    SIR_finally = "R";
                }
                else
                {
                    SIR_finally = "I";
                }
                return SIR_finally;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 查询所有药敏板信息
        /// </summary>
        private void ResultQuery()
        {
            if (!string.IsNullOrEmpty(Result_WellPlateID) ||
                StartDatePickerValue != null ||
                EndDatePickerValue != null)
                QueryConditionWellPlateID();
            else
                QueryAllWellPlateID();

            WPF.Controls.Message.Push($"药敏板列表查询成功！", MessageBoxImage.Information);
        }

        private void QueryConditionWellPlateID()
        {
            string[] temp;
            if (StartDatePickerValue != null || EndDatePickerValue != null)
                WellPlateItems = new ObservableCollection<WellPlateItem>(serviceImageProcessing.GetWellPlateItemsByTime(AppDomain.CurrentDomain.BaseDirectory + @"Image", StartDatePickerValue, EndDatePickerValue, hisRepository));
            else
                WellPlateItems = new ObservableCollection<WellPlateItem>(serviceImageProcessing.GetWellPlateItems(AppDomain.CurrentDomain.BaseDirectory + @"Image", hisRepository));

            if (!string.IsNullOrEmpty(Result_WellPlateID))
            {
                WellPlateItems = new ObservableCollection<WellPlateItem>(WellPlateItems.Where(o => o.WellPlateIDs.Any(id => id.Contains(Result_WellPlateID))));
            }
        }

        /// <summary>
        /// 改变模板
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private async void ChangeTemplate()
        {
            await Task.Run(() =>
            {
                switch (CurrentTemplate)
                {
                    case TemplateEnum.Default:
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            CurrentView = new Template_8x12() { DataContext = this }; //初始化窗口并导入当前界面
                            WellPlate = new WellPlate(96);                         //初始化数据源
                            PreviewWindowImageView = new ImageControl();
                            PreviewWindowImageSource = new Test();
                        });
                        break;
                    //case TemplateEnum.Test:
                    //    Application.Current.Dispatcher.Invoke(() =>
                    //    {
                    //        CurrentView = new Template_4x6() { DataContext = this };//初始化窗口并导入当前界面
                    //        WellPlate = new WellPlate(24);//初始化数据源
                    //        PreviewWindowImageView = new ImageControl();
                    //        PreviewWindowImageSource = new Test();
                    //    });
                    //    break;
                    default: break;
                }
            });
        }

        /// <summary>
        /// 修改为阳性
        /// </summary>
        /// <param name="index"></param>
        private void UpdatePositive(int index)
        {
            if (string.IsNullOrEmpty(WellPlate.ImageList[index].Result))
            {
                WPF.Controls.Message.Push("更新失败，当前不存在分析数据", MessageBoxImage.Warning);
                return;
            }
            string[] rets = WellPlate.ImageList[index].Result.Split('/');
            if (sbyte.Parse(rets[0]) >= 4)
            {
                rets[0] = "-1";
            }
            if (sbyte.Parse(rets[1]) >= 4)
            {
                rets[1] = "-1";
            }
            WellPlate.ImageList[index].Result = $"{rets[0]}/{rets[1]}/{rets[2]}";
            WellPlate.ImageList[index].IsUpdate = true;
            LoggerFactory.Instance.CurrentLogger.LogInfo($"{WellPlate.ID}第{index}的结果修改为阳性。");
            MessageBoxResult result = MessageBox.Show("是否重新进行结果报告分析？", "", MessageBoxButton.OKCancel, MessageBoxImage.Question);
            if (result == MessageBoxResult.OK)
                UpdateReport();
        }

        private void UpdateNegative(int index)
        {
            if (string.IsNullOrEmpty(WellPlate.ImageList[index].Result))
            {
                WPF.Controls.Message.Push("更新失败，当前不存在分析数据", MessageBoxImage.Warning);
                return;
            }
            string[] rets = WellPlate.ImageList[index].Result.Split('/');
            if (sbyte.Parse(rets[0]) < 4)
            {
                rets[0] = "10";
            }
            if (sbyte.Parse(rets[1]) < 4)
            {
                rets[1] = "10";
            }
            WellPlate.ImageList[index].Result = $"{rets[0]}/{rets[1]}/{rets[2]}";
            WellPlate.ImageList[index].IsUpdate = true;
            LoggerFactory.Instance.CurrentLogger.LogInfo($"{WellPlate.ID}第{index}的结果修改为阴性。");
            MessageBoxResult result = MessageBox.Show("是否重新进行结果报告分析？", "", MessageBoxButton.OKCancel, MessageBoxImage.Question);
            if (result == MessageBoxResult.OK)
                UpdateReport();
        }

        private void UpdateReport()
        {
            if (CurrentHis.IsSpecialSample)
            {
                Dictionary<int, string> bacteriaIndex = CurrentHis.SpecialSampleTypes
                                   .SelectMany(kv => kv.Value.Select(num => new { Number = num, Name = kv.Key })
                                   .OrderBy(x => x.Number)).ToDictionary(o => o.Number, o => o.Name);
                ShowSpecialSIR(bacteriaIndex);
            }
            else
            {
                string bacteriaName = CurrentHis.BacterialName;
                ShowSIR(bacteriaName);
            }
            AddOrUpdateReport(_report, CurrentHis, true);

            WellPlate.Report = _report;
        }

        /// <summary>
        /// 选择图片
        /// </summary>
        /// <param name="index">序号索引</param>
        private void SelectImage(int index)
        {
            if (!string.IsNullOrEmpty(WellPlate.ID))
            {
                if (WellPlate.SelectLocation != -1)
                {
                    WellPlate.ImageList[WellPlate.SelectLocation].BorderBrushColor = string.Empty;
                }
                WellPlate.ImageList[index].BorderBrushColor = "Black";
                WellPlate.SelectLocation = index;
                PreviewWindowImageSource = WellPlate.ImageList[index];
                PreviewWindowImageView = new ImageControl();
                //WPF.Controls.Message.Push($"选中了{index+1}号位", MessageBoxImage.Question);
            }
            else
            {
                WPF.Controls.Message.Push($"查看失败！当前页面暂时还未导入图片数据！", MessageBoxImage.Warning);
            }
        }

        /// <summary>
        /// 导出
        /// </summary>
        private async void Export()
        {
            ReportExportTemplate reportExportTemplate = new ReportExportTemplate()
            {
                DataContext = ViewModelLocator.ReportExportTemplateViewModel
            };
            App.Current.Dispatcher.Invoke(() =>
            {
                DialogHost.Show(reportExportTemplate, "Main");
            });
            return;
        }
    }
}
